package com.sss.springcloud.controller;

import com.alibaba.cloud.sentinel.datasource.RuleType;
import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.sss.springcloud.common.Result;
import com.sss.springcloud.entities.Payment;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;

/**
 * 流控规则测试
 * @author sss
 * @date 2020-03-11 19:31
 **/
@RestController
public class FlowLimitController {
    @Value("${server.port}")
    private String serverPort;
    /**
     * 按资源名称流控测试
    **/
    @GetMapping("/byResource")
    @SentinelResource(value = "byResource",blockHandler = "handlerException")
    public Result byResource(){
        return Result.succes("按资源名称测试ok",new Payment(220L,"serial"));
    }

    public Result handlerException(BlockException ex){
        return Result.fail(ex.getClass().getCanonicalName()+"\t服务不可用");
    }

    /**
     * 按资源URL流控规则测试
     **/
    @GetMapping("/byUrl")
    @SentinelResource(value = "byUrl")
    public Result byUrl(){
        return Result.succes("按URL名称测试ok",new Payment(221L,"serial"));
    }

    /**
     * 按用户自定义流控规则测试
     **/
    @GetMapping("/fallback/payment/get/{id}")
    @SentinelResource(value = "fallbackDemo",blockHandler = "handlerException2")
    public Result fallbackTest(@PathVariable("id") Integer id){
        if (id==5) {
            throw new IllegalArgumentException("参数不合法错误！！！"+serverPort);
        }else if (id==6){
            throw new RuntimeException("运行时异常！！！"+serverPort);
        }
        return Result.succes(new Payment(220L,"Flow自定义*****"));
    }


    public Result handlerException2(Integer id,BlockException ex){
        return Result.fail(444,"fallback兜底方法");
    }





}
